/**
 * 
 */
package com.java.test.user.mapper;

import com.java.test.user.dto.BlackIpInfo;
import com.java.test.util.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * @author 黑名单
 *
 */
@Component
public class BlackIpMapper {

	@Autowired
	private JdbcTemplate jdbcTemplate;

	public int selectBlackIpListCount(BlackIpInfo info) {
		String sql = "select count(*) from member_black_ip where 1=1 ";
		if (info.getUseStatus() != 0) {
			sql += " and use_status='" + info.getUseStatus() + "'";
		}
		if (info.getArea() != null && !"".equals(info.getArea())) {
			sql += "and area ='" + info.getArea() + "'";
		}

		if (info.getIpAddress() != null && !"".equals(info.getIpAddress())) {
			sql += "and ip_address like '%" + info.getIpAddress() + "%'";
		}
		Integer i = jdbcTemplate.queryForObject(sql, Integer.class);

		return i == null ? null : i;

	}

	public List<BlackIpInfo> selectBlackIpList(BlackIpInfo info, PageInfo<BlackIpInfo> page) {
		String sql = "select * from member_black_ip where 1=1 ";
		if (info.getUseStatus() != 0) {
			sql += " and use_status='" + info.getUseStatus() + "'";
		}
		if (info.getArea() != null && !"".equals(info.getArea())) {
			sql += "and area ='" + info.getArea() + "'";
		}

		if (info.getIpAddress() != null && !"".equals(info.getIpAddress())) {
			sql += "and ip_address like '%" + info.getIpAddress() + "%'";
		}

		int start = (page.getCurrentPage() - 1) * page.getPageCount();
		int limit = page.getPageCount();

		sql += "limit ?,?";
		List<BlackIpInfo> list = jdbcTemplate.query(sql, new BlackIpInfo(), start, limit);
		return list;
	}

	public List<BlackIpInfo> selectBlackIpList() {
		String sql = "select * from member_black_ip where use_status=1 ";
		List<BlackIpInfo> list = jdbcTemplate.query(sql, new BlackIpInfo());
		return list;
	}

	public int insertBlackIp(BlackIpInfo info) {
		String sql = "insert into member_black_ip(ip_address,area,use_count,use_status)values(?,?,?,?)";
		int i = jdbcTemplate.update(sql, info.getIpAddress(), info.getArea(), info.getUseCount(), info.getUseStatus());
		return i;
	}

	public int updateBlackStatus(BlackIpInfo info) {
		String sql = "update member_black_ip set use_status=? where id=?";
		int i = jdbcTemplate.update(sql, info.getUseStatus(), info.getId());
		return i;
	}

	public int deleteBlackIp(final int[] ids) {
		String sql = " delete from member_black_ip where id =?";
		jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
			public void setValues(PreparedStatement ps, int i) throws SQLException {
				ps.setInt(1, ids[i]);
			}

			public int getBatchSize() {
				return ids.length;
			}

		});
		return 1;

	}

}
